// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const wxContext = cloud.getWXContext()
    const dsName = event.dsName
    const id = event._id

    if (id) {
      const data = parseCmdData(event.data)
      return await db.collection(dsName).doc(id).update({
        data
      })
    }

    return await db.collection(dsName).add({
      data: {
        ...event.data,
        _openid: wxContext.OPENID
      }
    })

  } catch (e) {
    console.error(e)
    return e
  }
}

function parseCmdData(data) {
  const cmds = parseCmd(data)
  Object.keys(cmds).forEach(key => {
    data[key] = cmds[key]
  })

  return data
}

function parseCmd(data) {
  const res = {}
  Object.keys(data).forEach(key => {
    const value = data[key]
    if (!value.match) return

    const found = value.match(/_\.(?<cmd>\w+)\((?<param>[^\)]+)\)/)
    if (found) {
      res[key] = parseParam(found.cmd || found[1], found.param || found[2])
    }
  })

  return res
}

function parseParam(cmd, param) {
  const _ = db.command
  switch (cmd) {
    case 'inc':
      return _.inc(Number(param))
  }

  return null
}